package com.zzz.friend.service.exam.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zzz.common.core.domain.TableDataInfo;
import com.zzz.friend.domain.exam.Exam;
import com.zzz.friend.domain.exam.dto.ExamQueryDTO;
import com.zzz.friend.domain.exam.vo.ExamVO;
import com.zzz.friend.manager.ExamCacheManager;
import com.zzz.friend.mapper.exam.ExamMapper;
import com.zzz.friend.service.exam.ExamService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @BelongsProject: oj-project
 * @BelongsPackage: com.zzz.friend.service.exam.impl
 * @Author: zhai
 * @CreateTime: 2025-11-01  13:21
 * @Description: TODO
 * @Version: 1.0
 */
@Slf4j
@Service
public class ExamServiceImpl implements ExamService {

    @Autowired
    private ExamMapper examMapper;

    @Autowired
    private ExamCacheManager examCacheManager;

    /**
     * @description: 查询竞赛列表
     * @author: zhai
     * @date:  13:42
     * @param: [examQueryDTO]
     * @return: java.util.List<com.zzz.friend.domain.exam.vo.ExamVO>
     **/
    @Override
    public List<ExamVO> list(ExamQueryDTO examQueryDTO) {
        PageHelper.startPage(examQueryDTO.getPageNum(), examQueryDTO.getPageSize());
        List<ExamVO> examList = examMapper.list(examQueryDTO);
        return examList;
    }

    @Override
    public TableDataInfo redisList(ExamQueryDTO examQueryDTO) {
        log.info("开始从缓存中获取竞赛信息");
        Long total = examCacheManager.getExamListSize(examQueryDTO.getType(), null);
        List<ExamVO> examVOList;
        if (total == 0 || total == null) {
            log.info("缓存中没有数据，从数据库中获取数据");
            examVOList = list(examQueryDTO);
            // 刷新缓存
            examCacheManager.refreshCache(examQueryDTO.getType(), null);
            total = new PageInfo<>(examVOList).getTotal();
        } else {
            log.info("缓存中有数据");
            examVOList = examCacheManager.getExamVOList(examQueryDTO, null);
            total = examCacheManager.getExamListSize(examQueryDTO.getType(), null);
        }
        if (CollectionUtil.isEmpty(examVOList)) {
            return TableDataInfo.empty();
        }
        return TableDataInfo.success(examVOList, total);
    }


}
